package tictactoe.GUI;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import tictactoe.Player;
import tictactoe.exceptions.network.NetworkException;
import tictactoe.multiplayer.client.Client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;
import tictactoe.multiplayer.server.Server;

/**
 *
 * @author Home
 */
public class NewMultiplayer extends javax.swing.JDialog {

    private Client client;
    private PlayersTableRefresher thread;

    /**
     *
     * @param parent
     */
    public NewMultiplayer(java.awt.Frame parent) {
        super(parent, true);
        initComponents();
        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {
                System.err.println("bbbbbbbbbbbbbbbbbbbbbbbbbb");
                System.exit(1);
                System.exit(0);
                System.err.println("aaaaaaaaaaaaaaaaaaaaaaa");
            }
        });
        playersTable.setEnabled(false);
    }

    /**
     *
     * @param players
     */
    public void playersSetReceived(Collection<Player> players) {
        ((PlayersTableModel) playersTable.getModel()).setData(players);
    }

    /**
     *
     * @param cross
     * @param circle
     */
    public void startGame(Player cross, Player circle) {
        GameWindow gw = new GameWindow(JOptionPane.getFrameForComponent(this), client, cross, circle, 3);
        ((ClientImpl) client).setGameWindow(gw);
        thread.stopRefreshing();

        gw.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {

                System.err.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                System.exit(1);
                System.exit(0);

                System.err.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

            }
        });
        gw.setLocation(getLocation());
        setVisible(false);
        gw.setVisible(true);
        setLocation(gw.getLocation());
    }

    @Override
    public void dispose() {
        super.dispose();
        if (thread != null && !thread.isDone()) {
            thread.stopRefreshing();
        }
        if (client != null && client.isConnected()) {
            client.disconnect();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        content = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        server = new javax.swing.JTextField();
        connect = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        playersTable = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        name = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        btServer = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        content.setPreferredSize(new java.awt.Dimension(300, 200));

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("tictactoe/GUI/NewMultiplayer"); // NOI18N
        jLabel1.setText(bundle.getString("server")); // NOI18N

        server.setText("localhost");

        connect.setText(bundle.getString("connect")); // NOI18N
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        playersTable.setModel(new PlayersTableModel());
        jScrollPane1.setViewportView(playersTable);

        jLabel2.setText(bundle.getString("name")); // NOI18N

        name.setText("defaultName");

        jButton1.setText(bundle.getString("challenge")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btServer.setText("Сервер үүсгэх");
        btServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btServerActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout contentLayout = new javax.swing.GroupLayout(content);
        content.setLayout(contentLayout);
        contentLayout.setHorizontalGroup(
            contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentLayout.createSequentialGroup()
                .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, contentLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(name, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                            .addComponent(server, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE))
                        .addGap(10, 10, 10)
                        .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btServer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(connect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, contentLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        contentLayout.setVerticalGroup(
            contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(server, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btServer))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
                    .addGroup(contentLayout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addContainerGap())))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(content, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(content, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectActionPerformed
        try {
            client = new ClientImpl(server.getText(), this);
            client.connectClient(new Player(name.getText()));
            name.setEnabled(false);
            server.setEnabled(false);
            connect.setEnabled(false);
            thread = new PlayersTableRefresher(5000);
            thread.execute();
            playersTable.setEnabled(true);
            btServer.setEnabled(false);
        } catch (NetworkException ex) {
            JOptionPane.showMessageDialog(this, "Энэ ip дээр сервер алга.");
        }
    }//GEN-LAST:event_connectActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        int row = playersTable.getSelectedRow();
        if (row > -1) {
            Player p = ((PlayersTableModel) playersTable.getModel()).getPlayer(row);
            client.startGameWith(p);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btServerActionPerformed
        // Servertei holbohdoh heseg

        try {
            s = new Server();
            s.startServer();

            client = new ClientImpl("localhost", this);
            client.connectClient(new Player(name.getText()));
            name.setEnabled(false);
            server.setEnabled(false);
            connect.setEnabled(false);
            thread = new PlayersTableRefresher(5000);
            thread.execute();
            playersTable.setEnabled(true);
        } catch (NetworkException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Энэ ip дээр сервер үүсэх боломжгүй байна.");
        }
        btServer.setEnabled(false);
    }//GEN-LAST:event_btServerActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_formWindowClosed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btServer;
    private javax.swing.JButton connect;
    private javax.swing.JPanel content;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField name;
    private javax.swing.JTable playersTable;
    private javax.swing.JTextField server;
    // End of variables declaration//GEN-END:variables
    private Server s;

    private class PlayersTableModel extends AbstractTableModel {

        private List<Player> players = new ArrayList<Player>();

        public int getColumnCount() {
            return 1;
        }

        public int getRowCount() {
            return players.size();
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            if (columnIndex == 0) {
                return players.get(rowIndex).getName();
            } else {
                throw new IllegalArgumentException("columnIndex");
            }
        }

        @Override
        public String getColumnName(int column) {
            if (column == 0) {
                return ResourceBundle.getBundle("tictactoe/GUI/NewMultiplayer").getString("player");
            } else {
                throw new IllegalArgumentException("column");
            }
        }

        public void setData(Collection<Player> data) {
            players.clear();
            players.addAll(data);

            fireTableDataChanged();
        }

        public Player getPlayer(int row) {
            return players.get(row);
        }
    }

    private class PlayersTableRefresher extends SwingWorker<Integer, Collection<Player>> {

        private int delay;
        private boolean refresh;

        public PlayersTableRefresher(int delay) {
            this.delay = delay;
            refresh = true;
        }

        public void stopRefreshing() {
            refresh = false;
        }

        @Override
        protected Integer doInBackground() throws Exception {
            while (refresh) {
                client.askForPlayers();
                Thread.sleep(delay);
            }
            return 0;
        }
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        NewMultiplayer app = new NewMultiplayer(null);
        app.setVisible(true);
    }
}
